import {SimulationConfig, SimulationJobDefinition, SimulationRequestIn1} from "../common/simulator";
import {generateBusinessId, products} from "../common/util";
import * as _ from 'lodash';

export async function buildSimulationJobDefinition(params: string, simConfig?: SimulationConfig): Promise<SimulationJobDefinition> {
    const request: SimulationRequestIn1 = JSON.parse(params);
    const businessId = `${request.businessId || generateBusinessId()}`;
    const def: SimulationJobDefinition = {
        product: products.META,
        businessId,
        desc: request.desc || simConfig?.task?.desc || `meta simulation: ${businessId}`,
        spec: {
            runMode: simConfig?.runMode || 'native',
            model: {
                type: simConfig?.model?.type || 'remote',
                file: simConfig?.model?.file || '',
                entry: simConfig?.model?.entry || ''
            },
            result: {
                ossPath: '',
                specifiedLocalPath: simConfig?.result?.nativePath || '',
                uploadRawSimResult: simConfig?.outputSetup?.type.indexOf('file') > -1 ? true : false
            },
            config: request?.config || simConfig?.config || {},
            openGui: request?.openGui || simConfig?.openGui || false,
            extendedProperty: simConfig?.extra || {}
        }
    };

    if (request?.extra) {
        def.spec.extendedProperty = _.merge(JSON.parse(JSON.stringify(def.spec.extendedProperty)), request.extra);
    }

    let { model, outputParams, parameters: runtimeParameters } = request;

    // build model
    if (model?.file) {
        def.spec.model.file = model.file;
    }
    if (model?.entry) {
        def.spec.model.entry = model.entry;
    }
    if (model?.type) {
        def.spec.model.type = model.type;
    }

    // build input parameter
    let parameters = runtimeParameters || simConfig?.input || [];
    def.spec.parameters = parameters;

    // build output parameter
    let outputs = outputParams || simConfig?.output || [];
    def.spec.result.specifiedOutputParams = outputs;

    return def;
}